package org.mengyun.tcctransaction.sample.service;

import org.mengyun.tcctransaction.api.Compensable;
import org.mengyun.tcctransaction.sample.domain.dto.OrderDto;
import org.mengyun.tcctransaction.sample.domain.entity.TccOrder;
import org.mengyun.tcctransaction.sample.domain.repository.OrderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by changming.xie on 4/1/16.
 */
@Service
public class OrderService {

	@Autowired
	OrderRepository orderRepository;

	@Compensable(confirmMethod = "confirmCreateOrder", cancelMethod = "cancelCreateOrder", asyncConfirm = true)
	@Transactional
	public void tryCreateOrder(OrderDto od) {
		TccOrder o = new TccOrder();
		o.setProductId(od.getProductId());
		o.setUserId(od.getUserId());
		o.setTccStatus("0");
		orderRepository.save(o);
		od.setId(o.getId());// 设置订单id
	}

	public void confirmCreateOrder(OrderDto od) {
		TccOrder o = orderRepository.findById(od.getId()).get();
		o.setTccStatus("1");
		orderRepository.save(o);
	}

	public void cancelCreateOrder(OrderDto od) {
		orderRepository.deleteById(od.getId());
	}

}
